"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : DMS分布式锁
Case Name   : 角色获取锁、解锁、锁冲突操作
Create At   : 2023/4/21
Owner       : opentestcase033
Description :
    1.创建角色
    2.开启事务a，修改角色密码，不提交，事务b执行后提交
    3.开启事务b，重命名角色
    4.清理环境
Expect:
    1.设置成功
    2.执行成功，获取锁
    3.等锁释放，事务a提交(解锁)，事务b执行失败
    4.成功
History     :
"""

import os
import time
import unittest

from testcase.utils.Logger import Logger
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.ComThread import ComThread


class DmsOck(unittest.TestCase):

    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.pri_sh = CommonSH('PrimaryDbUser')
        self.constant = Constant()
        self.role = 'role_dms_ock_0016'

    def test_dms_ock(self):
        text1 = '-----step1:创建角色;expect:成功-----'
        self.log.info(text1)
        create_user = f"drop role if exists {self.role};" \
                      f"create role {self.role} password 'test@123';"
        create_user_res = self.pri_sh.execut_db_sql(create_user)
        self.log.info(create_user_res)
        self.assertIn(self.constant.CREATE_ROLE_SUCCESS_MSG, create_user_res,
                      f"执行失败:{text1}")

        text2 = '-----step2:开启事务a，修改角色密码，不提交，' \
                '事务b执行后提交;expect:执行成功，获取锁-----'
        self.log.info(text2)
        sql1 = f"start transaction;" \
               f"alter role {self.role} " \
               f"identified by 'abcd@123' replace 'test@123';" \
               f"select pg_sleep(3);" \
               f"commit;"
        session1 = ComThread(self.pri_sh.execut_db_sql, args=(sql1,))
        session1.setDaemon(True)
        session1.start()
        time.sleep(1)

        text3 = '-----step3:开启事务b，重命名角色;' \
                'expect:等锁释放，事务a提交(解锁)后，事务b执行失败-----'
        self.log.info(text3)
        sql2 = f"begin;alter role {self.role} rename to new_{self.role};"
        session2 = ComThread(self.pri_sh.execut_db_sql, args=(sql2,))
        session2.setDaemon(True)
        session2.start()
        session1.join(10)
        session2.join(10)
        result1 = session1.get_result()
        self.log.info(f'session1_results: {result1}')
        result2 = session2.get_result()
        self.log.info(f'session2_results: {result2}')
        self.assertIn(self.constant.START_TRANSACTION_SUCCESS_MSG,
                      result1, f"执行失败:{text2}")
        self.assertIn(self.constant.ALTER_ROLE_SUCCESS_MSG, result1,
                      f"执行失败:{text2}")
        self.assertIn(self.constant.COMMIT_SUCCESS_MSG, result1,
                      f"提交事务失败: {text3}")
        self.assertIn('ERROR:  tuple concurrently updated', result2,
                      f"重命名角色失败:{text3}")

    def tearDown(self):
        text4 = '-----step4:清理环境 expect:成功-----'
        self.log.info(text4)
        drop_res = self.pri_sh.execut_db_sql(
            f"drop user if exists {self.role} cascade;"
            f"drop user if exists new_{self.role} cascade;")
        self.log.info(drop_res)
        self.assertEqual(drop_res.count(self.constant.DROP_ROLE_SUCCESS_MSG), 2,
                         f"删除角色失败:{text4}")
        self.log.info(f'-----{os.path.basename(__file__)} end-----')
